#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#include <LoRa.h>
#include <DHT.h>
#include <BH1750.h>
#include <RTClib.h>
#include "ai_farm_analyzer.h"
#include "sensor_controller.h"
#include "irrigation_control.h"

// 定义引脚
#define DHTPIN 2
#define DHTTYPE DHT22
#define SOIL_MOISTURE_PIN A0
#define LORA_SS 10
#define LORA_RST 9
#define LORA_DIO0 3
#define RELAY_PUMP_PIN 4
#define RELAY_FAN_PIN 5
#define RELAY_LIGHT_PIN 6

// 初始化传感器
DHT dht(DHTPIN, DHTTYPE);
BH1750 lightMeter;
RTC_DS3231 rtc;

// 初始化传感器控制器
SensorController sensorController;

// 初始化灌溉控制器
IrrigationControl irrigationControl(RELAY_PUMP_PIN, RELAY_FAN_PIN, RELAY_LIGHT_PIN);

// 初始化AI农业分析器
AIFarmAnalyzer aiAnalyzer;

// 节点ID
const uint8_t nodeId = 1;

void setup() {
  // 初始化串口通信
  Serial.begin(9600);
  
  // 初始化I2C通信
  Wire.begin();
  
  // 初始化DHT传感器
  dht.begin();
  
  // 初始化光照传感器
  lightMeter.begin();
  
  // 初始化RTC
  if (!rtc.begin()) {
    Serial.println("无法初始化RTC模块！");
  }
  
  // 初始化LoRa模块
  LoRa.setPins(LORA_SS, LORA_RST, LORA_DIO0);
  if (!LoRa.begin(433E6)) {
    Serial.println("LoRa初始化失败！");
    while (1);
  }
  
  // 初始化传感器控制器
  sensorController.init();
  
  // 初始化灌溉控制器
  irrigationControl.init();
  
  // 初始化AI农业分析器
  aiAnalyzer.init();
  
  // 记录系统启动信息
  logEvent("系统启动");
}

void loop() {
  // 读取环境数据
  FarmEnvironmentData envData = sensorController.readAllSensors();
  
  // 添加时间戳
  DateTime now = rtc.now();
  envData.timestamp = now.unixtime();
  envData.hourOfDay = now.hour();
  
  // 使用AI分析器分析环境数据
  FarmRecommendation recommendation = aiAnalyzer.analyzeEnvironment(envData);
  
  // 执行智能控制
  irrigationControl.executeControl(recommendation);
  
  // 发送数据到网关
  sendDataToGateway(envData, recommendation);
  
  // 显示当前状态
  displayStatus(envData, recommendation);
  
  // 每5分钟采集一次数据
  delay(300000);
}

void sendDataToGateway(FarmEnvironmentData data, FarmRecommendation recommendation) {
  // 准备发送的数据
  LoRa.beginPacket();
  LoRa.write(nodeId);
  LoRa.write((uint8_t*)&data, sizeof(FarmEnvironmentData));
  LoRa.write((uint8_t*)&recommendation, sizeof(FarmRecommendation));
  LoRa.endPacket();
  
  Serial.println("数据已发送到网关");
}

void logEvent(String event) {
  // 记录事件到串口
  DateTime now = rtc.now();
  char timeString[20];
  sprintf(timeString, "%04d-%02d-%02d %02d:%02d:%02d",
          now.year(), now.month(), now.day(),
          now.hour(), now.minute(), now.second());
  Serial.print(timeString);
  Serial.print(": ");
  Serial.println(event);
}

void displayStatus(FarmEnvironmentData data, FarmRecommendation recommendation) {
  // 在串口打印当前状态
  Serial.println("--- 农业环境状态 ---");
  Serial.print("温度: ");
  Serial.print(data.temperature, 1);
  Serial.println(" °C");
  Serial.print("湿度: ");
  Serial.print(data.humidity, 1);
  Serial.println(" %");
  Serial.print("光照: ");
  Serial.print(data.lightIntensity, 0);
  Serial.println(" lux");
  Serial.print("土壤湿度: ");
  Serial.print(data.soilMoisture, 1);
  Serial.println(" %");
  Serial.print("CO2浓度: ");
  Serial.print(data.co2Level, 0);
  Serial.println(" ppm");
  
  if (recommendation.irrigate) {
    Serial.println("建议: 需要灌溉");
  } else {
    Serial.println("建议: 不需要灌溉");
  }
  
  if (recommendation.adjustVentilation) {
    Serial.println("建议: 调整通风");
  }
  
  if (recommendation.adjustLighting) {
    Serial.println("建议: 调整光照");
  }
  
  Serial.println("-------------------");
}